package cn.dxj1016.syn;
//不安全买票
//可能出现0或者-1
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"苦逼的我").start();
        new Thread(buyTicket,"牛逼的我").start();
        new Thread(buyTicket,"可恶的黄牛").start();
    }
}


class BuyTicket implements Runnable {
    //    票
    private int ticketNums = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
//        买票
        while (flag) {
            buy();
        }
    }
//synchronized 同步方法，锁的是this
    private  synchronized void buy() {
//        判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
//        模拟延迟
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "买到了" + ticketNums--);
    }
}